import { v4 as uuidv4 } from 'uuid';
import jsencrypt from './jsEncrypt.js';
const ossConf = require('../components/ali-oos/config.js');
var getWeek = function(){
	var d = new Date().getDay();
	var s = ['日','一','二','三','四','五','六'];
	return '星期'+s[d];
};
/**
 * 日期格式化
 */
var DateFormat = function(dtobj, format) {
	var o = {
		"M+": dtobj.getMonth() + 1, //month
		"d+": dtobj.getDate(), //day
		"h+": dtobj.getHours(), //hour
		"m+": dtobj.getMinutes(), //minute
		"s+": dtobj.getSeconds(), //second
		"q+": Math.floor((dtobj.getMonth() + 3) / 3), //quarter
		"S": dtobj.getMilliseconds() //millisecond
	}
	if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
		(dtobj.getFullYear() + "").substr(4 - RegExp.$1.length));
	for (var k in o)
		if (new RegExp("(" + k + ")").test(format))
			format = format.replace(RegExp.$1,
				RegExp.$1.length == 1 ? o[k] :
				("00" + o[k]).substr(("" + o[k]).length));
	return format;
}
var ObjEach = function(obj, fn) {
	var key, that = this;
	if (typeof fn !== 'function') return that;
	obj = obj || [];
	if (obj.constructor === Object) {
		for (key in obj) {
			if (fn.call(obj[key], key, obj[key])) break;
		}
	} else {
		for (key = 0; key < obj.length; key++) {
			if (fn.call(obj[key], key, obj[key])) break;
		}
	}
	return that;
};
var objSort = function(data, key, type) {
	//console.log("********************************************************")
	var arr = [],
		compare = function(obj1, obj2) {
			var value1 = obj1['history'][0][key];
			var value2 = obj2['history'][0][key];
			if (value2 < value1) {
				return -1;
			} else if (value2 > value1) {
				return 1;
			} else {
				return 0;
			}
		};
	// for(var key in data){
	// 	console.log(data[key])
	// 	arr.push(data[key]);
	// }
	ObjEach(data, function(index, item) {
		arr.push(item);
	});
	//console.log(arr);
	arr.sort(compare);
	if (type == "asc") arr.reverse();
	return arr;
};
var faces = function() {
	return ['😀','😃','😄','😁','😆','😅','🤣','😂','🙂','🙃','😉','😊','😇','🥰','😍','🤩','😘','😗','😚','😙','🥲','😋','😛','😜','🤪','😝','🤑','🤗','🤭','🤫','🤔','🤐','🤨','😐','😑','😶','😏','😒','🙄','😬','🤥','😌','😔','😪','🤤','😴','😷','🤒','🤕','🤢','🤮','🤧','🥵','🥶','🥴','😵','🤯','🤠','🥳','🥸','😎','🤓','🧐','😕','😟','🙁','😮','😯','😲','😳','🥺','😦','😧','😨','😰','😥','😢','😭','😱','😖','😣','😞','😓','😩','😫','🥱','😤','😡','😠','🤬','😈','👿','💀','🤡','👻','👽','🙈','🙉','🙊','💋','💌','💘','💝','💖','💗','💓','💞','💕','💟','💔','💯','💢','💥','💫','💦','💨','💤'];
}();
var transferContent = function(content) {
	content = (content || '').replace(/&(?!#?[a-zA-Z0-9]+;)/g, '&amp;')
		.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/'/g, '&#39;').replace(/"/g, '&quot;') //XSS
		.replace(/@(\S+)(\s+?|$)/g, '@<a href="javascript:;">$1</a>$2') //转义@
		.replace(/img\[([^\s]+?)\]/g, function(img) { //转义图片
			return "[图片]";
		})
		.replace(/file\([\s\S]+?\)\[[\s\S]*?\]/g, function(str) { //转义文件
			var href = (str.match(/file\(([\s\S]+?)\)\[/) || [])[1];
			var text = (str.match(/\)\[([\s\S]*?)\]/) || [])[1];
			if (!href) return str;
			return "[文件] " + text;
		})
		.replace(/audio\[([^\s]+?)\]/g, function(audio) { //转义音频
			return "[语音]";
		})
		.replace(/video\[([^\s]+?)\]/g, function(video) { //转义音频
			return "[视频]";
		})
		.replace(/json\[.*\]/g, function(json) { //转义json
			var str = json.replace(/(^json\[)|(\]$)/g, '');
			str = str.replace(/&amp;/g, '&');
			str = str.replace(/&lt;/g, '<');
			str = str.replace(/&gt;/g, '>');
			str = str.replace(/&quot;/g, '"');
			str = str.replace(/&#039;/g, "'");
			str = str.replace(/&#39;/g, "'");
			var obj = JSON.parse(str);
			return obj.title;
		});
	return content;
};
var transferContent2 = function(content) {
	content = (content || '').replace(/&(?!#?[a-zA-Z0-9]+;)/g, '&amp;')
		.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/'/g, '&#39;').replace(/"/g, '&quot;') //XSS
		.replace(/@(\S+)(\s+?|$)/g, '@<a href="javascript:;">$1</a>$2') //转义@
		.replace(/img\[([^\s]+?)\]/g, function(img) { //转义图片
			return "[图片]";
		})
		.replace(/file\([\s\S]+?\)\[[\s\S]*?\]/g, function(str) { //转义文件
			var href = (str.match(/file\(([\s\S]+?)\)\[/) || [])[1];
			var text = (str.match(/\)\[([\s\S]*?)\]/) || [])[1];
			if (!href) return str;
			return "[文件] " + text;
		})
		.replace(/audio\[([^\s]+?)\]/g, function(audio) { //转义音频
			return "[语音]";
		})
		.replace(/video\[([^\s]+?)\]/g, function(video) { //转义音频
			return "[视频]";
		})
		.replace(/json\[.*\]/g, function(json) { //转义json
			var str = json.replace(/(^json\[)|(\]$)/g, '');
			str = str.replace(/&amp;/g, '&');
			str = str.replace(/&lt;/g, '<');
			str = str.replace(/&gt;/g, '>');
			str = str.replace(/&quot;/g, '"');
			str = str.replace(/&#039;/g, "'");
			str = str.replace(/&#39;/g, "'");
			var obj = JSON.parse(str);
			return obj.title;
		});
	var reg = new RegExp('\n', "g");
	return content.replace(reg, '<br/>');
};
var transferContent3 = function(content) {
	content = (content || '').replace(/&(?!#?[a-zA-Z0-9]+;)/g, '&amp;')
		.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/'/g, '&#39;').replace(/"/g, '&quot;') //XSS
		.replace(/@(\S+)(\s+?|$)/g, '@<a href="javascript:;">$1</a>$2') //转义@
		.replace(/img\[([^\s]+?)\]/g, function(img) { //转义图片
			return '<img style="width:100%;" data-src="' + img.replace(/(^img\[)|(\]$)/g, '') + '" src="' + img.replace(
				/(^img\[)|(\]$)/g, '') + '">';
		})
		.replace(/file\([\s\S]+?\)\[[\s\S]*?\]/g, function(str) { //转义文件
			var href = (str.match(/file\(([\s\S]+?)\)\[/) || [])[1];
			var text = (str.match(/\)\[([\s\S]*?)\]/) || [])[1];
			if (!href) return str;
			return "[文件] " + text;
		})
		.replace(/audio\[([^\s]+?)\]/g, function(audio) { //转义音频
			return "[语音]";
		})
		.replace(/video\[([^\s]+?)\]/g, function(video) { //转义音频
			return "[视频]";
		})
		.replace(/json\[.*\]/g, function(json) { //转义json
			var str = json.replace(/(^json\[)|(\]$)/g, '');
			str = str.replace(/&amp;/g, '&');
			str = str.replace(/&lt;/g, '<');
			str = str.replace(/&gt;/g, '>');
			str = str.replace(/&quot;/g, '"');
			str = str.replace(/&#039;/g, "'");
			str = str.replace(/&#39;/g, "'");
			var obj = JSON.parse(str);
			return obj.title;
		});
	var reg = new RegExp('\n', "g");
	return content.replace(reg, '<br/>');
};
var transferDate = function(timestamp) {
	var n = new Date();
	var d = new Date(timestamp || new Date());
	if (n.getDate() == d.getDate() && n.getMonth() == d.getMonth() && n.getFullYear() == d.getFullYear()) {
		return digit(d.getHours()) + ':' + digit(d.getMinutes());
	} else if (n.getDate() == (d.getDate() + 1) && n.getMonth() == d.getMonth() && n.getFullYear() == d.getFullYear()) {
		return "昨天";
	} else {
		return digit(d.getFullYear()) + '/' + digit(d.getMonth() + 1) + '/' + digit(d.getDate());
	}
};
var transferDate2 = function(timestamp) {
	var n = new Date();
	var d = new Date(timestamp || new Date());
	if (n.getDate() == d.getDate() && n.getMonth() == d.getMonth() && n.getFullYear() == d.getFullYear()) {
		return digit(d.getHours()) + ':' + digit(d.getMinutes());
	} else if (n.getDate() == (d.getDate() + 1) && n.getMonth() == d.getMonth() && n.getFullYear() == d.getFullYear()) {
		return '昨天 ' + digit(d.getHours()) + ':' + digit(d.getMinutes());
	} else {
		return digit(d.getFullYear()) + '-' + digit(d.getMonth() + 1) + '-' + digit(d.getDate()) + ' ' + digit(d.getHours()) +
			':' + digit(d.getMinutes());
	}
};
var transferDate3 = function(timestamp) {
	var n = new Date();
	var d = new Date(timestamp || new Date());
	return digit(d.getFullYear()) + '年' + digit(d.getMonth() + 1) + '月' + digit(d.getDate()) + '日 ' + digit(d.getHours()) +
		':' + digit(d.getMinutes());
};
var transferDate4 = function(timestamp) {
	var n = new Date();
	var d = new Date(timestamp || new Date());
	return digit(d.getFullYear()) + '-' + digit(d.getMonth() + 1) + '-' + digit(d.getDate()) + ' ' + digit(d.getHours()) +
		':' + digit(d.getMinutes());
};
var digit = function(num, length, end) {
	var str = '';
	num = String(num);
	length = length || 2;
	for (var i = num.length; i < length; i++) {
		str += '0';
	}
	return num < Math.pow(10, length) ? str + (num | 0) : num;
};
var deepCopy = function(obj) {
	var _obj = JSON.stringify(obj),
		objClone = JSON.parse(_obj);
	return objClone;
};
var deepClone = function(obj) {
  let result;
  if (Array.isArray(obj)) {
    result = [];
  } else if (typeof obj === "object") {
    result = {};
  } else {
    return obj;
  }
  Object.keys(obj).forEach((key) => {
    if (typeof obj[key] === "object") {
      result[key] = deepClone(obj[key]);
    } else {
      result[key] = obj[key];
    }
  });
  return result;
};
var assignObject = function(target, source, excludes) {
  Object.keys(target).forEach((key) => {
    if (!(excludes == null ? void 0 : excludes.includes(key))) {
      target[key] = source[key];
    }
  });
  return target;
};
//四舍五入保留2位小数（若第二位小数为0，则保留一位小数
var keepTwoDecimal = function(num) {
	var result = parseFloat(num);
	if (isNaN(result)) {
		console.log("参数错误");
		return false;
	}
	result = Math.round(num * 100) / 100;
	var s_x = result.toString();
	var pos_decimal = s_x.indexOf('.');
	if (pos_decimal < 0) {
		pos_decimal = s_x.length;
		s_x += '.';
	}
	while (s_x.length <= pos_decimal + 1) {
		s_x += '0';
	}
	return s_x;
};
//四舍五入保留2位小数（不够位数，则用0替补）
var keepTwoDecimalFull = function(num) {
	var result = parseFloat(num);
	if (isNaN(result)) {
		console.log("参数错误");
		return false;
	}
	result = Math.round(num * 100) / 100;
	var s_x = result.toString();
	var pos_decimal = s_x.indexOf('.');
	if (pos_decimal < 0) {
		pos_decimal = s_x.length;
		s_x += '.';
	}
	while (s_x.length <= pos_decimal + 2) {
		s_x += '0';
	}
	return s_x;
};

var addressTransition = function(addressObj) {
	var data = {};
	if (addressObj) {
		for (var property in addressObj) {
			data['address[' + property + ']'] = addressObj[property];
		}
	}
	return data;
};
var getSuffix = function(filename) {
	var pos = filename.lastIndexOf('.');
	var suffix = '';
	if (pos != -1) {
		suffix = filename.substring(pos);
	}
	return suffix;
};
var sendRequest = function(that, url, method, auto_hide_indicator, data) {
	var sign = getSign(that);
	return new Promise((resolve, reject) => {
		uni.request({
			url: that.ApiUrl + url,
			method: method || 'GET',
			dataType: 'json',
			header: {
				'content-type': 'application/x-www-form-urlencoded',
				'appid': that.appId,
				'sign': sign,
				'authorization': that.userInfo ? that.userInfo.access_token : ''
			},
			data: data || {},
			success: (res) => {
				if (auto_hide_indicator) {
					if (that.indicator) {
						that.indicator = 0;
					}
					uni.hideLoading();
				}
				if (res.data.code == 0) {
					if(res.data.data){
						resolve(res.data.data);
					}
					else{
						resolve(res.data);
					}
				} else if (res.data.code == 401) {
					//登录过期
					that.removeUserInfo();
					that.loginOut();
					//that['userModule/logout']();
					//reject(res.data.msg);
				} else {
					reject(res.data.msg);
				}
			},
			fail: (res) => {
				reject("网络错误");
			}
		});
	});
};
var getSign = function(that){
    var timestamp=new Date().getTime();
    return jsencrypt.setEncrypt(that.rsa_publickey,timestamp.toString());
};
var uuid = function() {
	return uuidv4();
};
var toPage = function(e){
	if(e.currentTarget.dataset['url']){
		uni.navigateTo({
			url:e.currentTarget.dataset['url'],
			animationType:e.currentTarget.dataset['animationtype'] || 'slide-in-right',
			fail:function(e){
				uni.showToast({
					title: '即将上线,敬请期待.',
					icon: 'none'
				});
			}
		})
	}
	else{
		uni.showToast({
			title: '即将上线,敬请期待.',
			icon: 'none'
		});
	}
};
var ossUrl = function(){
	return ossConf.fileHost;
};
var closeIndicator = function(that){
	that.animation = "page-mark-fade-out";
};

var showIndicator = function(that) {
	that.animation = "";
};
var formatMoney = function(val,pre,suf){
	var newStr = val.split('').reverse().join("");
	newStr = newStr.replace(',',">naps/<万>'naw'=ssalc naps<");
	newStr = newStr.replace(',',">naps/<亿>'iy'=ssalc naps<");
	newStr = newStr.split('').reverse().join("");
	if(pre){
		newStr = "<span class='pre'>"+pre+"</span>"+newStr;
	}
	if(suf){
		newStr = newStr+"<span class='suf'>"+suf+"</span>";
	}
	return newStr;
	
};
var upx2px = function(val){
	return uni.upx2px(val);
};
var isNull = function(str){
	if(str === null || str === undefined || str.length === 0) {
		return true;
	  }
	  else{
		return false;
	  }
	  
};
module.exports = {
	getWeek: getWeek,
	DateFormat: DateFormat,
	objSort: objSort,
	deepCopy: deepCopy,
	transferContent: transferContent,
	transferContent2: transferContent2,
	transferContent3: transferContent3,
	transferDate: transferDate,
	transferDate2: transferDate2,
	transferDate3: transferDate3,
	transferDate4: transferDate4,
	faces: faces,
	keepTwoDecimal: keepTwoDecimal,
	keepTwoDecimalFull: keepTwoDecimalFull,
	addressTransition: addressTransition,
	getSuffix: getSuffix,
	sendRequest: sendRequest,
	uuid: uuid,
	toPage: toPage,
	ossUrl:ossUrl,
	closeIndicator:closeIndicator,
	showIndicator:showIndicator,
	formatMoney:formatMoney,
	deepClone:deepClone,
	assignObject:assignObject,
	upx2px:upx2px,
	isNull:isNull,
	getSign:getSign
}
